package top.leyi.handle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.leyi.IService.IFileStorgeService;
import top.leyi.exception.FileSizeOutofRangeException;
import top.leyi.exception.FileTypeNotSupportException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
public class FileUploadHandle {
    @Autowired
    IFileStorgeService fileStorgeService;

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Map<String, ? super Object> fileUpload(@RequestParam("file") MultipartFile file)throws IOException, FileSizeOutofRangeException,FileTypeNotSupportException {

        String code = "";

        if(file.getSize() > 1024 * 1024){
            throw new FileSizeOutofRangeException();
        }

       /*
        * 获取文件后缀名
        */
       String [] strs = file.getOriginalFilename().split("\\.");
       String suffix = "." + strs[strs.length - 1];

       String[] allowedFileType = {
               ".jpg",".png"
       };
       /*
         检测是否使用了正确的文件格式
        */
       boolean allowed = false;
       for(String type : allowedFileType){
           if(type.equals(suffix)){
               allowed = true;
               break;
           }
       }
       if(!allowed){
         throw new FileTypeNotSupportException();
       }

      /*
       * service
       */

       Map<String, ? super Object>  map = new HashMap<>();
       map.put("code", "200");
       map.put("data", fileStorgeService.storgeImage(file.getInputStream(), suffix));
       return  map;
    }

}
